package com.yst.gateway.monitor.common.filters;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yst.gateway.monitor.common.utils.LoginUserCache;
import com.yst.gateway.monitor.models.SysUsers;

/**
 * 简单的权限过滤类
 * @author sheungxin
 *
 */
public class JumpFilter implements Filter{
	/*允许访问的路径*/
	private static List<String> noFilterList=new ArrayList<String>();
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request =(HttpServletRequest) req;
		HttpServletResponse response =(HttpServletResponse) res;
		String uri=request.getRequestURI();
		String contextPath=request.getContextPath()+"/";
		String path=uri.substring(contextPath.length());
		if(isNoFilter(path)){
			chain.doFilter(req, res);
		}else{
			//判断用户是否登录
			SysUsers sysUser=LoginUserCache.getUser();
			if(sysUser!=null){
				//判断用户自有权限，待处理
				chain.doFilter(req, res);
			}else{
				response.sendError(403);
			}
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		noFilterList.add("bootstrap-dist");
		noFilterList.add("css");
		noFilterList.add("font-awesome");
		noFilterList.add("img");		
		noFilterList.add("js");
		noFilterList.add("sys/users/loginIn");
		noFilterList.add("sys/users/loginOut");
		noFilterList.add("login.jsp");
		noFilterList.add("");
	}
	
	private boolean isNoFilter(String path){
		boolean flag=false;
		if(noFilterList.contains(path)){
			flag=true;
		}
		if(!flag){
			path=path.substring(0,path.indexOf("/"));
			flag=noFilterList.contains(path);
		}
		return flag;
	}

}
